﻿using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace VoteInformationSystem.Models
{
    public class NpgsqlQRCodesRepository : IQRCodeRepository
    {
        public bool IsValid(string qrcode)
        {
            int count = -1;

            using (NpgsqlConnection pgConnection = NpgsqlConnectionProvider.GetConnection())
            using (NpgsqlCommand command = new NpgsqlCommand("select count(*) from \"QRCodes\" where \"code\" = :qrcode and \"used\" = false", pgConnection))
            {
                command.Parameters.Add(new NpgsqlParameter("qrcode", NpgsqlTypes.NpgsqlDbType.Text));
                command.Prepare();
                command.Parameters.First<NpgsqlParameter>().Value = qrcode;
                count = (int)System.Convert.ToInt32(command.ExecuteScalar());
            }
            if (count == 1)
            {
                markAsUsed(qrcode);
                return true;
            }
            else
            {
                return false;
            }
        }

        private void markAsUsed(String qrcode)
        {
            using (NpgsqlConnection pgConnection = NpgsqlConnectionProvider.GetConnection())

            using (NpgsqlCommand command = new NpgsqlCommand("update \"QRCodes\" set \"used\" = true where \"code\" = :qrcode", pgConnection))
            {
                command.Parameters.Add(new NpgsqlParameter("qrcode", NpgsqlTypes.NpgsqlDbType.Varchar));
                command.Prepare();
                command.Parameters.First<NpgsqlParameter>().Value = qrcode;
                command.ExecuteNonQuery();
            }
        }
    }
}